﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization;
using System.Net;
using HashMaster.Lib;
using System.Threading;
using System.IO;

namespace HashMaster.Monitor
{
    public partial class frmMain : Form
    {
        private string ServiceUrl = "http://localhost:1170/";
        
        private int CheckInterval = 10;
        //private int SliceWidth = 1;
        private int ActiveTimeout = 300;
        Thread thdChkAlive;
        FileSystemWatcher watcher;

        private List<Client> DeadClients = new List<Client>();

        private DateTime CheckAliveLastRun;

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            //ServiceUrl = "http://larvata.info/hm/";
            ServiceUrl = "http://localhost:1456/";

            CheckAliveLastRun = DateTime.Now;

            thdChkAlive = new Thread(new ThreadStart(CheckAlive));
            thdChkAlive.Start();
            xmpp = new XmppClientConnection("gmail.com");
            xmpp.Password = "123456abc!";
            xmpp.Username = "larvata.bot";
            xmpp.ConnectServer = "talk.google.com";
            xmpp.OnLogin+=new ObjectHandler(xmpp_OnLogin);
            
            xmpp.KeepAlive = true;
            xmpp.Open();

            watcher = new FileSystemWatcher();
            watcher.Path = Application.StartupPath+@"\IMEI";
            //watcher.NotifyFilter = NotifyFilters.CreationTime;
            //watcher.Filter = "*.ini";
            watcher.Created+=new FileSystemEventHandler(watcher_Created);
            watcher.EnableRaisingEvents = true;
        }

        void watcher_Created(object sender, FileSystemEventArgs e)
        {
            string rawImei;
            string rawSha;
            int count = 0;
            int err = 0;
            using (StreamReader reader = new StreamReader(new FileStream(e.FullPath,FileMode.Open)))
            {
                while (!reader.EndOfStream)
                {
                    rawImei = reader.ReadLine();
                    if (rawImei.Length == 0) continue;
                    if (rawImei.Substring(0,1) == "[" && rawImei.Substring(rawImei.Length-1,1) == "]")
                    {
                        rawImei = rawImei.Substring(1, rawImei.Length - 3);
                        rawImei = "00" + rawImei + "00";
                        rawSha = reader.ReadLine();
                        rawSha = rawSha.Substring(4);

                        ClientSyncData ret= Utility.AddNewTask(rawImei, rawSha, 5, ServiceUrl);

                        if (ret.ErrorCode==0)
                        {
                            count++;
                        }
                        else
                        {
                            err++;
                        }
                        
                    }
                }
            }
            File.Delete(e.FullPath);
            MessageBox.Show("新增 " + count.ToString() + "个任务，" + err.ToString()+" 个重复");
        }


        void xmpp_OnLogin(object sender)
        {
            UpdateFormText(" (Gtalk Logined)");
            //throw new NotImplementedException();
           
        }

        delegate void UpdateFormTextDelegate(string newText);
        private void UpdateFormText(string newText)
        {


            if (this.InvokeRequired == true)
            {
                UpdateFormTextDelegate del = new UpdateFormTextDelegate(UpdateFormText);
                this.Invoke(del, new object[] { newText });
            }
            else
            {
                this.Text+= newText;
            }
        }

        delegate void UpdateListDataSourceDelegate();
        private void UpdateListDataSource() 
        {
            if (lstDeadClients.InvokeRequired==true)
            {
                UpdateListDataSourceDelegate del = new UpdateListDataSourceDelegate(UpdateListDataSource);
                lstDeadClients.Invoke(del);
            }
            else
            {
                lstDeadClients.DataSource = null;
                lstDeadClients.DisplayMember = "ClientName";
                lstDeadClients.DataSource = DeadClients;
                
                //lstDeadClients.Items.re
            }
        }


        /// <summary>
        /// 检测无响应客户机
        /// </summary>
        private void CheckAlive() 
        {
            
            while (true)
            {
                while (DateTime.Now.Subtract(CheckAliveLastRun).TotalSeconds > CheckInterval)
                {
                    string errMessage = string.Empty;
                    CheckAliveLastRun = DateTime.Now;
                    List<Client> clients = Utility.GetAllClients(ServiceUrl);
                    bool HasDeadClient = false;

                   

                    foreach (Client c in clients)
                    {
                        ///客户机超时 禁用并添加到无响应列表
                        if (DateTime.Now.Subtract(c.LastActive).TotalSeconds > ActiveTimeout)
                        {
                            if (HasDeadClient==false)
                            {
                                DeadClients.Add(new Client { ClientName = DateTime.Now.ToLongDateString() +" "+DateTime.Now.ToLongTimeString() });
                                HasDeadClient = true;
                            }
                            errMessage+= c.ClientName + "\r";
                            DeadClients.Add(c);
                            Utility.SetClientDeactive(ServiceUrl, c);
                        }
                    }

                    if (HasDeadClient==true)
                    {
                        DeadClients.Add(new Client { ClientName = "---------------------------" });
                    }
                    

                    ///刷新错误记录控件
                    //lstDeadClients.DataSource = DeadClients;
                   UpdateListDataSource();
                    //lstDeadClients.DataSource = new List<Client>() { new Client { ClientName = "aabb" } };


                    ///gtalk登陆正常 发送警报
                    if (xmpp.Authenticated&&errMessage.Length>0)
                    {
                        string message;
                        message = string.Format("{1}\r{0}\r以下主机未响应：\r{2}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString(), errMessage);
                        xmpp.Send(new ags.Message("alzzlnewtype@gmail.com", ags.MessageType.chat,message));
                        xmpp.Send(new ags.Message("dofeel@gmail.com", ags.MessageType.chat, message));

                    }
                }
                Thread.Sleep(1000);
            }



            
        }

        private void btnPreferences_Click(object sender, EventArgs e)
        {
            new frmPreference().ShowDialog(this);
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            thdChkAlive.Abort();
            xmpp.Close();
        }

        private void btnInput_Click(object sender, EventArgs e)
        {
            var tmpArr = txtInput.Text.Split(':');
            ClientSyncData ret = Utility.AddNewTask(tmpArr[1], tmpArr[0],5, ServiceUrl);
            if (ret.ErrorCode!=0)
            {
                MessageBox.Show("add task error");
            }
            else
            {
                MessageBox.Show("SUCCESS");
            }
        }
    }
}
